package tech.veedo.munchkin.beans.basic.thread;

import java.util.Optional;
import java.util.function.Function;

public class Either<L, R> {

    private L left;

    private R right;

    private Either(L left, R right) {
        this.left = left;
        this.right = right;
    }

    public Either<L, R> left(L left) {
        this.left = left;
        return this;
    }

    public Either<L, R> right(R right) {
        this.right = right;
        return this;
    }

    public static <L, R> Either<L, R> Left(L value) {
        return new Either(value, null);
    }
    public static <L, R> Either<L, R> Right(R value) {
        return new Either(null, value);
    }

    public boolean isLeft() {
        return left != null;
    }
    public boolean isNotLeft() {
        return left == null;
    }
    public boolean isRight() {
        return right != null;
    }
    public boolean isNotRight() {
        return right == null;
    }

    public <T> Optional<T> mapLeft(Function<? super L, T> mapper) {
        if (isLeft()) {
            return Optional.of(mapper.apply(left));
        }
        return Optional.empty();
    }
    public <T> Optional<T> mapRight(Function<? super R, T> mapper) {
        if (isRight()) {
            return Optional.of(mapper.apply(right));
        }
        return Optional.empty();
    }

    public String toString() {
        if (isLeft()) {
            return "Left(" + left +")";
        }
        return "Right(" + right +")";
    }

}
